//
//  HomeViewModel.swift
//  AgricultureApp
//
//  Created by eport_user1 on 2018/1/10.
//  Copyright © 2018年 eport_user1. All rights reserved.
//

import UIKit
import SwiftyJSON
import Alamofire
typealias aSuccessClose = ([HomeModel],Bool) -> Void
typealias aFailureClose = (Any) -> Void

class HomeViewModel: NSObject {
    
    

    class func laodData(page:Int,finishBlock:@escaping(aSuccessClose),failureBlock:@escaping aFailureClose) -> Void {
        
       
        
        var param = [String:Any]()
        param["current_page"] = page
        
        Alamofire.request(UrlNews, method: .get, parameters: param).responseJSON { (respond) in
            
            let result = respond.result
            
            switch(result){
                
            case let .success(value):
                
                let jsonData = JSON.init(value)
                
                var modelsArray = [HomeModel]()
                let reultArray = jsonData["data"]["list"].arrayObject
                
                for reDic in reultArray!{
                    
                    if ((reDic as? [String:Any]) != nil) {
                        
                        let model = HomeModel.init(dict: reDic as! [String : Any])
                        modelsArray.append(model)
                        
                    }
                }
                
                
                let isHaveNext = jsonData["data"]["has_next_page"].boolValue
                
                finishBlock(modelsArray,isHaveNext)
                
 
            case let .failure(error):
                print(error)
                
                failureBlock(error)
                
            }
            
        }

    }
}
